package cn.jas.common.jascommon.util;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;
/**
 * @description: 文件处理工具类
 * @author: chen_mx
 **/
public class FileUtils {

    public  static final  String []  filetypes={".doc",".docx",".xls",".xlsx",".txt"};
    private static  String   diskPath;

    /** 根据系统类型 调整路径中的分隔符 */
    public  static  String  convertSystemFilePath(String  path){
        String  system= System.getProperty("os.name").toLowerCase();

        if(system.indexOf("window")>=0){
           return  path.replace("/",File.separator);
        }
        if(system.indexOf("linux")>=0){
            return path.replace("\\",File.separator);
        }
        return  path;
      // /upload/2019-05-19/2019-05-195151f4c7-5f73-4aa4-bebe-30d26808d3d8.docx
    }


    /** 获取文件名称 不含路径*/
    public static  String  getFileName(String url){
        if(url!=null || url.indexOf(File.separator)!=-1){
            return  url.substring(url.lastIndexOf("\\")+1,url.indexOf("."));
        }
        return "";
    }

    /** 获取文件类型 */
    public  static String  getExtName(String fileName){
        if(fileName.indexOf(".")!=-1){
            String extName=fileName.substring(fileName.lastIndexOf("."));
            return  extName;
        }
        return "";
    }
    /** 获取路径加上文件名**/
    public  static  String  getDiskPathAndFileName(String instancePath){
        if(instancePath.indexOf(".")!=-1){
            String  spath=instancePath.substring(0,instancePath.indexOf("."));
            return  spath;
        }
        return "";
    }


    public  static String  getHttpPrefix(HttpServletRequest request){
        return  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/file";
    }


    public  static  boolean   isLinux(){
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if(os.startsWith("Win")||os.startsWith("win")){
            return  false;
        }
        return  true;
    }

    /** 获取实体路径  **/
    public  static  String   getInstanceFilePath(String url,HttpServletRequest request){
        if(url.indexOf(request.getContextPath())!=-1){
            return  url.substring(url.indexOf(request.getContextPath())+request.getContextPath().length());
        }
        return url;
    }
    /** 获取实体路径  **/
    public  static  String   getInstanceFileUrl(String url){
        if(url.indexOf("upload")!=-1){
            return  url.substring(url.indexOf("upload")-1);
        }
        return url;
    }

    /** 判断是文档资源还是视频资源*/
    public  static  boolean   isDocumentType(String url){
        String  suffix=getExtName(url);
        List<String>  list= Arrays.asList(filetypes);
        if(list.contains(suffix)){
              return true;
        }
        return false;
    }

    /**
     * 删除服务数据文件
     * /upload/***.doc
     * **/
    public  static  boolean   deleteFile(String url){
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(url)){
                File file=new File(url);
                if(file.isFile()){
                    file.delete();
                }else {
                   File [] fl=file.listFiles();
                    for(File s:fl){
                        deleteFile(s.getAbsolutePath());
                    }
                    file.delete();
                }
                return  true;
        }
        return false;
    }



   /* public static void main(String[] args) {

        System.out.println(deleteFile("D:\\data\\123123"));
        *//*String  str="/upload/2019-05-19/2019-05-19172ab63a-2786-4663-b0a0-306e62d3e34a.docx";
        //System.out.println(isDocumentType(str));
        System.out.println(convertSystemFilePath(str));*//*
    }*/



    public  static  boolean  isFileType(String url,String pdffix){
       if(org.apache.commons.lang3.StringUtils.equals(getExtName(url),pdffix)){
            return  true;
       }
       return  false;
    }


    /**
     * 上传图片
     *  原名称
     * @param request 请求
     * @param path_deposit 存放位置(路径)
     * @param file 文件
     * @param isRandomName 是否随机名称
     * @return 完整文件路径
     */
    public static String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName, String  staticPath) {
        //上传
        try {
            String[] typeImg={"gif","png","jpg","docx","doc","xls","xlsx","pdf","mp4"};
            if(file!=null){
                String origName=file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:"+origName);
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                         /** 存放到自定位置 filepath*/

                        File root=null;
                        if(StringUtils.isEmpty(staticPath)){
                            root= ResourceUtils.getFile("classpath:").getParentFile().getParentFile().getParentFile();
                        }else {
                            root=new  File(staticPath);
                        }
                        System.out.println("root"+root.getAbsolutePath());
                        System.out.println("deposit"+path_deposit);
                        StringBuffer sb=new StringBuffer();
                        sb.append(root.getAbsoluteFile());
                        File  filePath=new File(sb.toString());
                        if(!filePath.exists()){
                            filePath.mkdirs();
                        }
                        //存放图片文件的路径
                        //String path=request.getSession().getServletContext().getRealPath(path_deposit);
                        String path=filePath.getAbsolutePath()+path_deposit;
                        System.out.println("path:>>>>>>>>"+path);
                        //组合名称
                        String fileSrc="";
                        //是否随机名称
                        if(isRandomName){
                            origName=DateUtil.formateString(new Date(), "yyyy-MM-dd")+ UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
                        }
                        //判断是否存在目录
                        File targetFile=new File(path,origName);
                        System.out.println("t"+targetFile.getAbsolutePath());
                        if(!targetFile.exists()){
                            if(targetFile.isFile()){
                                targetFile.createNewFile();
                            }else {
                                targetFile.mkdirs();//创建目录
                            }
                        }
                        //上传
                        file.transferTo(targetFile);
                        /** 转换 图片尺寸  **/
                        String  img=FileUtils.getExtName(targetFile.getPath());
                        String [] types={".jpg",".png"};
                        if(Arrays.asList(types).contains(img)){
                            int  height=672;
                            int  width=384;
                            resizeImg(height,width,targetFile.getPath());
                        }
                        //完整路径
                        fileSrc=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+path_deposit+origName;
                        System.out.println("图片上传成功:"+fileSrc);
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 改变图片的尺寸
     *
     * @param newWidth, newHeight, path
     * @return boolean
     */
    public static  boolean resizeImg(int newWidth, int newHeight, String path) {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));

            //字节流转图片对象
            BufferedImage bi = ImageIO.read(in);

            //构建图片流
            BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            //绘制改变尺寸后的图
            tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
            //输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(tag);
            ImageIO.write(tag, "PNG", out);
            in.close();
            out.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 改变图片的大小到宽为size，然后高随着宽等比例变化
     * @param is 上传的图片的输入流
     * @param os 改变了图片的大小后，把图片的流输出到目标OutputStream
     * @param size 新图片的宽
     * @param format 新图片的格式
     * @throws IOException
     */
    public static boolean resizeImage(String resourcePath,String  targetPath, int size, String format) throws IOException {
        BufferedInputStream  in=null;
        BufferedOutputStream os=null;
        try{
            in = new BufferedInputStream(new FileInputStream(resourcePath));
            //字节流转图片对象
            BufferedImage bi = ImageIO.read(in);
            os = new BufferedOutputStream(new FileOutputStream(targetPath));
            //字节流转图片对象
            //BufferedImage prevImage = ImageIO.read(in);
            double width = bi.getWidth();
            double height = bi.getHeight();
            double percent = size/width;
            int newWidth = (int)(width * percent);
            int newHeight = (int)(height * percent);
            BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
            Graphics graphics = image.createGraphics();
            graphics.drawImage(bi, 0, 0, newWidth, newHeight, null);
            ImageIO.write(image, format, os);
            os.flush();
            in.close();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }finally {
            if(os!=null){
              os.close();
            }
            if(in!=null){
                in.close();
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String  path="D:\\root\\file\\upload\\2019-06-18\\test1.jpg";
        String  path1="D:\\root\\file\\upload\\2019-06-18\\test1_back.jpg";
        int  height=672;
        int  width=384;
       // resizeImg(height,width,path);
        try {
            resizeImage(path,path1,width,"png");
            System.out.println("输出完成");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
